import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  getMenuList,
  addMenu,
  updateMenu,
  deleteMenu,
  executeSyncAPIMenu,
  backupMenuDataToJson
} from "@/api/system";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

import { hasAuths } from "@/router/utils";
import { any } from "vue-types";

export function useMenu() {
  const form = reactive({
    title: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const menuDataList = ref([]);
  const loading = ref(true);

  const getMenuType = (type: string, text: boolean = false): string => {
    switch (type) {
      case "Menu":
        return text ? "菜单" : "primary";
      case "Iframe":
        return text ? "iframe" : "warning";
      case "Link":
        return text ? "外链" : "danger";
      case "Button":
        return text ? "按钮" : "info";
      default:
        throw new Error(`未知的菜单类型：${type}`);
    }
  };

  interface TreeNode {
    id: string;
    menuId: string;
    meta: any;
    name: string | null;
    parentId: string | null;
    path: string | null;
    redirect: string | null;
    component: string | null;
    children?: TreeNode[];
    level: number; // 新增的节点等级属性
    title: string;
  }

  function buildTree(menus: TreeNode[]): TreeNode[] {
    const map: { [key: string]: TreeNode } = {};
    const tree: TreeNode[] = [];

    menus.forEach(menu => {
      menu.title = menu?.meta?.title;
      map[menu.id] = menu;
      menu.children = [];
    });

    menus.forEach(menu => {
      if (menu.parentId !== null && map[menu.parentId]) {
        const parentLevel = map[menu.parentId].level || 0;
        menu.level = parentLevel + 1;
        map[menu.parentId].children.push(menu);
      } else {
        menu.level = 0;
        tree.push(menu);
      }
    });
    return tree;
  }

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row?.meta?.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{transformI18n(row?.meta?.title)}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "menuType",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getMenuType(row?.meta?.type)}
          effect="plain"
        >
          {getMenuType(row?.meta?.type, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "path"
    },
    {
      label: "组件路径",
      prop: "component"
      // formatter: ({ path, component }) =>
      //   isAllEmpty(component) ? path : component
    },
    {
      label: "权限标识",
      prop: "code"
    },
    {
      label: "排序",
      prop: "rank",
      width: 100,
      cellRenderer: ({ row, props }) => row?.meta?.rank
    },
    {
      label: "隐藏",
      prop: "hidden",
      cellRenderer: ({ row, props }) =>
        row?.meta?.hidden === true ? "是" : "否",
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation",
      hide: !hasAuths(["menu:add", "menu:id", "menu:delete:ids"])
    }
  ];

  async function handleExecuteSyncAPIMenu() {
    await executeSyncAPIMenu();
    message(`同步成功`, {
      type: "success"
    });
    onSearch();
  }

  async function handlebackupMenuDataToJson() {
    await backupMenuDataToJson();
    message(`备份成功`, {
      type: "success"
    });
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getMenuList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    let newData = data;
    if (!isAllEmpty(form.title)) {
      // 前端搜索菜单名称
      newData = newData.filter(item =>
        transformI18n(item.title).includes(form.title)
      );
    }

    menuDataList.value = data;
    dataList.value = buildTree(newData); // 处理成树结构
    loading.value = false;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          higherMenuOptions: buildTree(cloneDeep(menuDataList.value)),
          id: row?.id ?? null,
          menuId: row?.menuId ?? null,
          parentId: row?.parentId ?? null,
          name: row?.name ?? null,
          path: row?.path ?? null,
          redirect: row?.redirect ?? null,
          component: row?.component ?? null,
          code: row?.code ?? null,
          url: row?.url ?? null,
          httpMethods: row?.httpMethods ?? null,
          menuType: row?.menuType ?? null,
          meta: row?.meta ?? { hidden: false },
          /** meta */
          title: row?.meta?.title ?? null,
          icon: row?.meta?.icon ?? null,
          active: row?.meta?.active ?? null,
          color: row?.meta?.color ?? null,
          type: row?.meta?.type ?? null,
          fullpage: row?.meta?.fullpage ?? null,
          hidden: row?.meta?.hidden ?? false,
          tag: row?.meta?.tag ?? null,
          rank: row?.meta?.rank ?? 1
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(
            `您${title}了菜单名称为${transformI18n(curData.title)}的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              await addMenu(curData);
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              await updateMenu(curData);
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    await deleteMenu(row);
    message(`删除成功`, {
      type: "success"
    });
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange,
    handleExecuteSyncAPIMenu,
    handlebackupMenuDataToJson
  };
}
